
from ninja import Router, ModelSchema
from blog.models import Ziyuan
from utils.response import Response
from django.db.models import Q

router = Router()

class SchemaOut(ModelSchema):
    class Config:
        model = Ziyuan
        model_fields = ['id', 'name', 'weblink', 'default_passcode']


@router.get("/ziyuan/list")
def list_archives(request, current: int, size: int, searchkey: str = ''):
    # 初始化一个空的 Q 对象列表  
    q_objects = Q()  
    
    # 如果 searchkey 存在且不为空  
    if searchkey and searchkey.strip():  
        # 你可以添加多个字段的搜索条件，使用 | 表示逻辑或  
        q_objects &= (  
            Q(name__icontains=searchkey)
        )  
    count = Ziyuan.objects.filter(q_objects, is_del=0).count()
    ziyuan = Ziyuan.objects.filter(q_objects, is_del=0).order_by('-create_time').values('id', 'create_time', 'name', 'weblink', 'default_passcode')
    _ziyuan = [z for z in ziyuan]
    offset = size * (current - 1)
    limit: int = size
    recordList = _ziyuan[offset: offset + limit]
    return Response({"count": count, "recordList": recordList})
